const fs = require('fs');  
const axios = require('axios');
const fileTool = require('./file');  

function removeLastCharacter(str, charToRemove) {  
  if (str.endsWith(charToRemove)) {  
      return str.slice(0, -1); // 使用slice从字符串的开始到倒数第二个字符  
  }  
  return str; // 如果没有找到要移除的字符，则返回原始字符串  
}  


async function search(win, inFile, outFile, cover) {
  try {
    if (!fileTool.isFile(inFile) || !fileTool.isFile(outFile)) {
      return {err:"文件路径有误，请确认"}
    }

    let oldData = fs.readFileSync(outFile, 'utf8'); 
    let oldDataLines = oldData.split("\n")
  
    let regex = /[ 	]*\["workshop-(\d+)"]/g;  
    let matchData = []
    let str = ""
    const data = fs.readFileSync(inFile, 'utf8')
  
    for (const match of data.matchAll(regex)) {
      matchData.push(match[0])
  
      let hasOld = false //旧数据是否存在
      if (!cover) { //不覆盖更新
        oldDataLines.map((v)=>{
          if (v.indexOf(match[1]) > -1) {
            hasOld = true
          }
        })
      }
  
      if (!hasOld) {
        let name = await getName(match[1])
        str += "ServerModSetup(\"" + match[1] + "\") --" + name + "\r\n"
        win.webContents.send('name-update', name)
      }
    }
  
    if (!cover) { //拼接新旧数据再写入
      oldData = removeLastCharacter(oldData, "\n")
      oldData = removeLastCharacter(oldData, "\r")
      str = oldData + "\r\n" + str
    }
    fs.writeFileSync(outFile, str);  
  
    return {matchData, str}
  } catch (err) {
    return {err}
  }
}

async function getName(number) {
  const url = 'https://www.wegame.com.cn/api/rail/rpc/rail.UserSpaceServer.QueryItems?ie=utf-8&oe=utf-8';
  const data = "{\"sw_ids\":[\"" + number + "\"],\"with_detail\":true,\"with_metadatas\":true,\"with_rail_tags\":true,\"stamp\":{\"session_id\":{\"guid\":\"2883935f-0dac-4200-8af8-8a7d6b59b7a3\"},\"agent_client_language\":\"zh_CN\"}}"

  try {
    let response = await axios.post(url, JSON.parse(data))
    if (response.data.retcode == 0){
      return response.data.items[0].name
    }
  } catch (error) {
    
  }
  return ""
}


module.exports = {
  search
}